﻿using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Description;

namespace Sharp.Infrastructure.Wcf
{
    public class HttpBindingServiceHostFactory : ServiceHostFactory
    {
        private static readonly ConcurrentDictionary<Type, Type> ServiceContracts;
        private static readonly BasicHttpBinding Binding;
        static HttpBindingServiceHostFactory()
        {
            ServiceContracts = new ConcurrentDictionary<Type, Type>();
            Binding = new BasicHttpBinding("ServiceProxyBinding");

        }
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            var host = base.CreateServiceHost(serviceType, baseAddresses);

            //把契约缓存起来
            if (!ServiceContracts.Keys.Contains(serviceType))
            {
                var contracts =
                    ((TypeInfo)serviceType).ImplementedInterfaces.Single(y => y != typeof(IApplicationServiceContract));
                ServiceContracts.TryAdd(serviceType, contracts);
            }

            ServiceEndpoint se = host.AddServiceEndpoint(ServiceContracts[serviceType], Binding, "");
            se.Behaviors.Add(new ContextPropagationBehavior());


            return host;
        }
    }

}
